// app.js
const httpUtils = require('./utils/httpUtils')
const ui = require('./utils/ui')
App({
  onLaunch() {
    // 登录
    var _this = this
    wx.getStorage({
      key: "token",
      success(res) {
        console.log("已登录")
        _this.getInfo()
      },
      fail(err) {
        wx.login({
          success(res) {
            if (res.code) {
              //发送请求
              httpUtils.request({
                method: "POST",
                showLoading: true,
                url: `/api/auth/wx_login`,
                message: "正在登录...",
                data: { code: res.code },
              }).then(res => {
                if (res.data.code != 0) {
                  ui.showToast(res.mes)
                } else {
                  wx.setStorage({
                    key: "token",
                    data: res.data.data.access_token
                  })
                  _this.getInfo()
                }
              }).catch(err => {
                console.log('ERROR')
              });
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          }
        })
      }
    })

  },
  getInfo() {
    var _this = this
    // 获取用户信息
    httpUtils.request({
      method: "POST",
      showLoading: true,
      url: `/api/auth/info`,
      message: "获取账号信息...",
    }).then(res => {
      // console.log(res)
      if (res.data.code != 0) {
        ui.showToast(res.data.mes)
      } else {
        _this.globalData.isLogin = true,
          _this.globalData.userInfo = res.data.data
      }
    }).catch(err => {
      console.log(err)
    });
  },
  onShow() { },
  globalData: {
    isLogin: false,
    userInfo: null
  }
})
